from django.db.models import Count
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.filters import OrderingFilter
from rest_framework.response import Response

from news import models
from news import serializers
from django_filters.rest_framework import DjangoFilterBackend,FilterSet
import django_filters
from rest_framework.pagination import PageNumberPagination

# Create your views here.

class CatePage(PageNumberPagination):
    page_size = 3
    page_size_query_param = 'page_size'

class NewsPage(PageNumberPagination):
    page_size = 3
    page_size_query_param = 'page_size'

class NewsFie(FilterSet):
    titles = django_filters.CharFilter(field_name='title',lookup_expr='contains')
    aut = django_filters.CharFilter(field_name='author')
    show = django_filters.BooleanFilter(field_name='is_show')
    reads = django_filters.NumericRangeFilter(field_name='read',lookup_expr='range')
    ti = django_filters.DateFilter(field_name='add_time',lookup_expr='gte')
    class Meta:
        model = models.News
        fields = ['titles','aut','show','reads','ti']


class CateView(viewsets.ModelViewSet):
    queryset = models.Cate.objects.all()
    serializer_class = serializers.CateSer
    pagination_class = CatePage

    @action(detail=False, methods=['get'])
    def br(self, request):
        news = models.Cate.objects.annotate(num=Count('news')).values('name','num').order_by('-num')
        return Response(news[0:3])

class NewsView(viewsets.ModelViewSet):
    queryset = models.News.objects.all()
    serializer_class = serializers.NewsSer

    pagination_class = NewsPage
    filter_backends = [DjangoFilterBackend,OrderingFilter]
    filterset_class = NewsFie

    ordering_fields = ['read']
    ordering = ['read']



    def retrieve(self, request,pk):
        a = models.News.objects.filter(id=pk).first()
        a.read+=1
        a.save()
        return Response(super().retrieve(request,pk).data)

        # return Response({'mes':'查询成功'})



    @action(methods=['put'], detail=True)
    def brs(self, request, pk):
        a = models.News.objects.filter(id=pk).first()
        a.is_show = request.data.get('is_show')
        a.save()
        return Response({'msg': 'ok'})


